package com.pengpeng.flash.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pengpeng.flash.common.BaseContext;
import com.pengpeng.flash.common.CustomException;
import com.pengpeng.flash.entity.*;
import com.pengpeng.flash.mapper.OrderMapper;
import com.pengpeng.flash.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    /**
     * 用户下单
     * @param orders
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        //获取当前登录用户的id
        long currentId = BaseContext.getCurrentId();
        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        if (list == null || list.size() == 0){
            throw new CustomException("购物车为空，无法下单...");
        }

        //获取用户信息
        User user = userService.getById(currentId);
        //获取地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null){
            throw new CustomException("用户地址信息有误，无法下单...");
        }

        //获取订单号
        long orderId = IdWorker.getId();

        //原子整数类，保证线程安全
        AtomicInteger amount = new AtomicInteger(0);

        //循环遍历每一个购物车对象，为订单明细对象赋值
        List<OrderDetail> orderDetails = list.stream().map((item)->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);  //绑定订单号
            orderDetail.setNumber(item.getNumber());  //绑定当前菜品或者套餐的份数
            orderDetail.setDishFlavor(item.getDishFlavor());  //口味
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());  //单份金额
            //计算总金额:单份价钱乘以数量
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //向订单表插入数据
        orders.setNumber(String.valueOf(orderId));  //设置订单号
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());  //订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());  //结账时间
        orders.setStatus(2);  //设置订单状态，1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAmount(new BigDecimal(amount.get()));  //计算总金额
        orders.setUserId(currentId);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());  //设置收货人
        orders.setPhone(addressBook.getPhone());  //设置手机号
        orders.setAddress((addressBook.getProvinceName()==null?"":addressBook.getProvinceName())  //设置地址
                +(addressBook.getCityName()==null?"":addressBook.getCityName())
                +(addressBook.getDistrictName()==null?"":addressBook.getDistrictName())
                +(addressBook.getDetail()==null?"":addressBook.getDetail()));
        this.save(orders);

        //想订单明细表插入数据
        orderDetailService.saveBatch(orderDetails);
        //清空购物车数据
        shoppingCartService.remove(queryWrapper);
    }
}
